/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.auth;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

/**
 * @author oldcrane<br/>
 * @created 2019-06-09
 */
public class CustomSessionManager extends DefaultWebSessionManager {

	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
//		Enumeration<String> headNames =httpServletRequest.getHeaderNames();
//		while(headNames.hasMoreElements()) {
//			String key = headNames.nextElement();
//			System.out.println("heade key:" + key + ",value:" + httpServletRequest.getHeader(key));
//		}

		final String HEADER_KEY = "authorization";
		//final String PREFIX = "Bearer ";
		String token = httpServletRequest.getHeader(HEADER_KEY);
		if (!StringUtils.isEmpty(token)) {
			String sessionId = token;
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, HEADER_KEY);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return token;
		} else {
			return super.getSessionId(request, response);
		}
	}

}
